<?php

namespace App\Admin\Controllers;

use App\Models\CompanyModel;
use App\Models\UserModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;

class CompanyController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '公司列表';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new CompanyModel());
       // $grid->disableCreateButton();

        $grid->filter(function ($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            // 关联查询
            $filter->where(function ($query){
                $query -> whereHas('user',function ($query){
                    $query -> where('nickname','like',"%".$this -> input."%");
                });
            },'用户名');

        });

        $grid->column('id', __('Id'));

        $grid->column('company_name', '公司名称')->style('display:table-cell;vertical-align:middle;text-align:center;');

        $grid->column('Invitation_code', '企业邀请码')->style('display:table-cell;vertical-align:middle;text-align:center;');

        $grid->column('max_number','允许加入的最大人数');

        $grid->column('employees_number','员工人数')->style('display:table-cell;vertical-align:middle;text-align:center;');

        $grid->column('company_address','地址')->style('display:table-cell;vertical-align:middle;text-align:center;');

        $grid->column('Industry_description', '备注')->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('created_at','创建时间')->style('display:table-cell;vertical-align:middle;text-align:center;');

        $grid->export(function ($export) {
            $export->originalValue(['created_at']);
        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(CompanyModel::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('user_id', '用户');
        $show->field('company_name', '公司名称');
        $show->field('Invitation_code', '邀请码');
        $show->field('max_number','允许加入的最大人数');
        $show->field('employees_number','员工人数');
        //$show->field('industry_type', '行业类型');
        //$show->field('apply_sketch', '申请描述');

        $show->field('company_address','地址');
        //$show->field('last_used_at', __('Last used at'));
        $show->field('Industry_description', '备注');
        $show->field('created_at','创建时间');
        $show->field('updated_at', '更新时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new CompanyModel());

        $form->text('company_name', '公司名称');
        $form->text('Invitation_code', '邀请码');

        $form->text('company_address','地址');

        $form->textarea('Industry_description', '备注');

        $form->number('max_number', '允许加入的最大人数');

        $form->select('status', '公司审核')->options([
            '1'=>'未审核',
            '2'=>'不通过',
            '3'=>'通过审核',
            '4'=>'审核不通过',
        ]);

        $form->select('upload_permission', '是否可以使用企业后台上传书籍')->options([
            '1'=>'是',
            '2'=>'否',
        ]);

        $form->text('company_account', '分配企业后台账号')->rules('required|min:6', [
            'required'=>'不能为空',
            'min'   => 'code不能少于6个字符',
        ])
            ->updateRules(['required', "unique:company_users,username,{{id}}"]);

        $form->text('company_password', '分配企业账号后台密码')->rules('required|min:5', [
            'required'=>'不能为空',
            'min'   => 'code不能少于5个字符',
        ]);

        //保存前回调
        $form->saved(function (Form $form) {

            $data = $_REQUEST;
            //插入laravel-admin 企业后台权限控制表
            //dd($form->status,$form->company_account,$form->company_password);
            $company_account = $form->model()->company_account;
            $company_password = $form->model()->company_password;
            $status = $form->status;
            if($status == 3 && !empty($company_account) && !empty($company_password)){
                //dd(1111);
                DB::beginTransaction(); //开启事务
                try{
                    $user_id = \DB::table('company_users')->insertGetId([
                        'username'=>$company_account,
                        'password'=> bcrypt($company_password),
                        'name'=> $company_account,
                        'company_id'=> $form->model()->id,
                        'created_at'=> date('Y-m-d H:i:s'),
                    ]);
                    //dd($user_id);
                    \DB::table('company_user_permissions')->insert([
                        'user_id'=>$user_id,
                        'permission_id'=> 1,
                        'created_at'=> date('Y-m-d H:i:s'),
                    ]);
                    \DB::table('company_role_users')->insert([
                        'role_id'=>2,
                        'user_id'=>$user_id,
                        'created_at'=> date('Y-m-d H:i:s'),
                    ]);

                    DB::commit();

                }catch (\Exception $e) {
                    //dd($e);
                    //接收异常处理并回滚
                    $error = new MessageBag([
                        'title'   => '保存错误',
                        'message' => '保存错误.',
                    ]);
                    DB::rollBack();
                    return back()->with(compact('error'));
                }
            }

        });

        return $form;
    }
}
